package com.longe.fastdfs.controller;

import com.longe.fastdfs.util.FileDfsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileController {

    @Autowired
    private FileDfsUtil fileDfsUtil;

    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {

        String fileUrl = fileDfsUtil.uploadFile(file);
        if(StringUtils.isEmpty(fileUrl)){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败");
        }
        return ResponseEntity.ok(fileUrl);
    }

    /**
     * 文件下载
     */
    @GetMapping(value = "/download")
    public ResponseEntity<String> downloadFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            fileDfsUtil.downloadFile(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载失败");
        }
        return ResponseEntity.ok("SUCCESS");
    }

    /**
     * 文件删除
     */
    @GetMapping(value = "/delete")
    public ResponseEntity<String> deleteFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            fileDfsUtil.deleteFile(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
        }
        return ResponseEntity.ok("SUCCESS");
    }
}